/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.eit.ntc.lmsbackend.struts.action;


import com.eit.ntc.lmsbackend.struts.form.LMSForm;
import com.eit.ntc.lmsbackend.utils.RoleUtils;
import com.eit.ntc.spring.utils.DateTimeUtils;
import com.eit.ntc.struts.action.AbstractWebFlowAction;
import com.eit.toschoolonline.lms.jdo.EntranceItemM;
import com.eit.toschoolonline.lms.jdo.LearningItemM;
import com.eit.toschoolonline.lms.jdo.LessonM;
import com.eit.toschoolonline.lms.jdo.SubjectM;
import com.eit.toschoolonline.lms.service.EntranceItemService;
import com.eit.toschoolonline.lms.service.LearningItemService;
import com.eit.toschoolonline.lms.service.LessonService;
import com.eit.toschoolonline.lms.service.SubjectService;


import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.sound.midi.SysexMessage;
import org.apache.struts.upload.FormFile;
import org.springframework.validation.Errors;
import org.springframework.webflow.execution.Event;
import org.springframework.webflow.execution.RequestContext;

/**
 *
 * @author chanon
 */
public class EentranceAction extends AbstractWebFlowAction{
        private LessonService lessonService;
        private SubjectService subjectService;
        private EntranceItemService entranceItemService;
        private LearningItemService learningItemService;


    public Event saveUpdateFileEn(RequestContext context) throws Exception {
            LMSForm lForm = (LMSForm) getFormObject(context);
            String zipfileFlag = getHttpServletRequestParameter(context, "zipfile");
            Errors errors = getFormErrors(context);
            boolean iszip = false;
            if (zipfileFlag!=null && zipfileFlag.trim().equals("iszip")){ 
                iszip = true;
            };
            // FormFile dFile = getFormFile(context,"docFile");
             String dFileName = (String) getHttpServletSessionAttribute(context, "temp_filename");
            System.out.println("file name:"+dFileName);
            removeHttpServletSessionAttribute(context, "temp_filename");
             File dFile = new File(dFileName);
            long dFileSize = 0;
            if (dFile!=null){

                dFileName = dFile.getName();

                dFileSize = dFile.length();
            };
           // System.out.println("+++++++++++++++++++++++++++++++++++"+dFile.getContentType());
            if(dFile!=null && !dFileName.equals("") && dFileSize>0){
                EntranceItemM item = lForm.getEntranceItemM();
                String filename = getHttpServletRequestParameter(context, "docFilename");
                if (filename==null || filename.trim().equals("")){
                    
                    if (iszip){
                        errors.reject("errors.UploadZipFileName");
                        return error();
                    }
                    filename = (String) getHttpServletSessionAttribute(context, "temp_name");
                    removeHttpServletSessionAttribute(context, "temp_name");
                };
                item.setFilename(filename);
                int nextItemCode = learningItemService.getMaxItemCode();
                item.setItemCode(nextItemCode+1);
                item = entranceItemService.updateEn(item,dFile,iszip);
                lForm.setEntranceItemM(item);

                return success();
            } else {
               // Errors errors = getFormErrors(context);
                errors.rejectValue("docFile", "errors.FileNotFound", "File Not Found");
                return error();
            }
        }
        public Event cancelUpdateFileEn(RequestContext context) throws Exception {
            return success();
        }

    public Event MainEntrance(RequestContext context) throws Exception {
         
          LMSForm lForm = (LMSForm) getFormObject(context);
          lForm.setSubjectM(null);
         
          lForm.getLessonList().clear();
          lForm.getSubjectList().clear();
          lForm.getEntranceList().clear();
          lForm.setSelectSubject("");
          lForm.getItemList().clear();
          lForm.setActiveSelect("");
          String yearThai = DateTimeUtils.dateToThaiStringFormat(DateTimeUtils.getThaiNow(), "yyyy");
          int yearThaiInt = Integer.parseInt(yearThai);
          List yearList = new ArrayList();
          for (int i=20;i>=1;i--){
              int tempInt = yearThaiInt -i;
              yearList.add(tempInt);
          };
          yearList.add(yearThaiInt);
          for (int i=1;i<=10;i++){
              int tempInt = yearThaiInt +i;
              yearList.add(tempInt);
          };
          lForm.setYearLabelList(yearList);
          lForm.setSelectNumber("1");
          
          //lForm.setActiveSelect("");
          SubjectService sservice = getSubjectService();
          lForm.setSubjectList(sservice.getSubjectAll());
          return new Event(this, "success");
        } 
    
    public Event GetActiveEntrance(RequestContext context) throws Exception {
         LMSForm lForm = (LMSForm) getFormObject(context);   
          SubjectService sservice = getSubjectService();
          lForm.getItemList().clear();     
          SubjectM s =sservice.getSubjectByCode(lForm.getSelectSubject());
          lForm.setSubjectM(s);        
          
          EntranceItemService eservice = getEntranceItemService();
          
          lForm.setEntranceList(eservice.getEnBySubject(s));
          return new Event(this, "success");
        } 
    
    public Event AddEntrance(RequestContext context) throws Exception {
               LMSForm lForm = (LMSForm) getFormObject(context);      
               lForm.setEnName("");
               lForm.setEnOwner("");
              // System.out.println("add page");
               Date thaiDate = DateTimeUtils.getThaiNow();
              // System.out.println("thai date:"+thaiDate);
               String year = DateTimeUtils.formatThaiDate(thaiDate, "yyyy");
              // System.out.println("year:"+year);
               lForm.setSelectYear(year);
               lForm.setErrorMode("");
               lForm.setSelectNumber("");
               lForm.setEnFileName("");
               lForm.setEnDocType(EntranceItemM.ENTRNACE_DOC_TYPE);
               lForm.setEnFileType(EntranceItemM.TELE_ITEM_TYPE);
              // lForm.setZipfile(false);
               //lForm.setSubjectM(null);
               lForm.setActiveSelect("");
               lForm.setItemDescription("");
               lForm.setItemKeyword("");
               lForm.setEnType(EntranceItemM.ENTRNACE);
             return new Event(this, "success");
        } 
    
     public Event SelectEntranceSubject(RequestContext context) throws Exception {
          LMSForm lForm = (LMSForm) getFormObject(context);
          lForm.setActiveSelect("OPEN");
          SubjectService sservice = getSubjectService();
          SubjectM s = sservice.getSubjectByCode(lForm.getSelectSubject());
          LessonService lservice = getLessonService();
          LessonM l =lservice.getLessonEntrance(s.getSubjectCode());
         
          lForm.setLessonM(l);
          lForm.setSubjectM(s);          
          return new Event(this, "success");
        } 
     public Event DelEntrance(RequestContext context) throws Exception {
         LMSForm lForm = (LMSForm) getFormObject(context);
                EntranceItemService eservice = getEntranceItemService();
                EntranceItemM e = eservice.getEn(Integer.parseInt(lForm.getInputID()));
                 e.setStatus(LearningItemM.DELETE_STATUS);
                eservice.updateEn(e);
                lForm.setSelectSubject(lForm.getSubjectM().getSubjectCode());
                return new Event(this, "success");    
        } 
      public Event EditEntrance(RequestContext context) throws Exception {
                LMSForm lForm = (LMSForm) getFormObject(context);
                EntranceItemService eservice = getEntranceItemService();
                String itemID = getHttpServletRequestParameter(context,"id");
                EntranceItemM e = eservice.getEn(Integer.parseInt(itemID));
                lForm.setEnName(e.getEnName());
                lForm.setErrorMode("");
                lForm.setEnFileType(e.getType());
                lForm.setEnOwner(e.getOwner());
                lForm.setSelectYear(e.getYear());
                lForm.setSelectNumber(e.getNumber());
                //lForm.setZipfile(false);
                lForm.setItemDescription(e.getItemDesc());
                lForm.setItemKeyword(e.getKeyword());
                lForm.setEnDocType(e.getEntDocType());
                lForm.setEntranceItemM(e);
             return new Event(this,"success");
        }
      
      
        public Event SaveEditEntrance(RequestContext context) throws Exception {
             
        LMSForm lForm = (LMSForm) getFormObject(context);        
//        LessonService lservice = getLessonService();
//        LearningItemService liservice = getLearningItemService();
//        LessonM l = lservice.getLesson(Integer.parseInt(lForm.getSelectLesson()));
//        FormFile dFile = getFormFile(context,"itemFile");
//                lForm.getItemFile();
//        //Create Path
//        String path ="";
//        
//            path = "c:/learningitem/"+dFile.getFileName();
// 
//      //  Read & write File
//       
//        byte[] dFileData = dFile.getFileData();
//        
//        FileOutputStream fosDown = new FileOutputStream(path);
//                fosDown.write(dFileData);
//                fosDown.close();
//            
         EntranceItemM itemM = lForm.getEntranceItemM();
         itemM.setUpdateDate(DateTimeUtils.getEngNow());
         //itemM.setFilename(lForm.getItemName());
         
         itemM.setEnName(lForm.getEnName());
         itemM.setNumber(lForm.getSelectNumber());
         itemM.setOwner(lForm.getEnOwner());
         itemM.setType(lForm.getEnFileType());
         itemM.setYear(lForm.getSelectYear());
        // itemM.setUserRole();
         itemM.setItemDesc(lForm.getItemDescription());
         itemM.setKeyword(lForm.getItemKeyword());
      
         EntranceItemService eservice = getEntranceItemService();
        
        
         
        
         
         eservice.updateEn(itemM);
         return new Event(this, "success");
        } 
       public Event SaveEntrance(RequestContext context) throws Exception {
             
        LMSForm lForm = (LMSForm) getFormObject(context);
        SubjectService sservice = getSubjectService();
        Errors errors = getFormErrors(context);
        SubjectM s = sservice.getSubjectByCode(lForm.getSelectSubject());
            String zipfileFlag = getHttpServletRequestParameter(context, "zipfile");
            boolean iszip = false;
            if (zipfileFlag!=null && zipfileFlag.trim().equals("iszip")){
                iszip = true;
            };
        lForm.setSubjectM(s);

        lForm.setErrorMode("");
        EntranceItemService eservice = getEntranceItemService();
        LearningItemService liservice = getLearningItemService();
        int max = liservice.getMaxItemCode()+1;  
        FormFile dFile = getFormFile(context,"enFile");
       if(dFile.getFileName()!=null && !dFile.getFileName().equals("")){ 
        //Create Path
//        String path ="";
//         path = pathEentrance+"/"+max+"/"+dFile.getFileName();
//         if(lForm.getDocType().equals("flashpaper")){
//            path = "c:/ntc/eentrance/flashpaper/"+max+"/"+dFile.getFileName();
//         }else if(lForm.getDocType().equals("html")){
//            path = "c:/ntc/eentrance/html/"+max+"/"+dFile.getFileName();
//         }else if(lForm.getDocType().equals("swfvdo")){
//            path = "c:/ntc/eentrance/swfvdo/vdo/"+max+"/"+dFile.getFileName();
//         }else if(lForm.getDocType().equals("wma")){
//            path = "c:/ntc/eentrance/wma/vdo/"+max+"/"+dFile.getFileName();
//         }
//         System.out.println("path:"+path);
//        File pathFile = new File(path);
//        File newpath = pathFile.getParentFile();
//        newpath.mkdirs();
      //  Read & write File
       
        byte[] dFileData = dFile.getFileData();
        
//        FileOutputStream fosDown = new FileOutputStream(path);
//                fosDown.write(dFileData);
//                fosDown.close();
           
         EntranceItemM itemM = new EntranceItemM();
         itemM.setCreateDate(DateTimeUtils.getEngNow());
         String enFileName = lForm.getEnFileName();
         if (enFileName==null || enFileName.trim().equals("")){
                if (iszip){
                     errors.reject("errors.UploadZipFileName");
                    return error();
                }


             enFileName = dFile.getFileName();
         };
         itemM.setFilename(enFileName);
//         if(lForm.getDocType().equals("swfvdo") || lForm.getDocType().equals("wma")){
//            itemM.setLink(lForm.getDocType()+"/vdo/"+max+"/"+itemM.getFilename());
//         }else{
//            itemM.setLink(lForm.getDocType()+"/"+max+"/"+itemM.getFilename());
//         }
         itemM.setItemCode(max);
         itemM.setItemType(LearningItemM.E_ENTRANS_TYPE);
         itemM.setType(lForm.getEnFileType());
         //itemM.setLessonId(lForm.getLessonM());
         //itemM.setLessonName(lForm.getLessonM().getLessonName());
         itemM.setStatus(EntranceItemM.ENABLE_STATUS);
         itemM.setSubjectName(lForm.getSubjectM().getSubjectName());
         itemM.setYear(lForm.getSelectYear());
         itemM.setEnName(lForm.getEnName());
         itemM.setNumber(lForm.getSelectNumber());
         String enFileTypeTemp = lForm.getEnFileType();
         if (lForm.getEnDocType()!=null && lForm.getEnDocType().trim().equals(EntranceItemM.OTHER_DOC_TYPE)){
             enFileTypeTemp = getHttpServletRequestParameter(context, "enFileTypeSelect");
             itemM.setEntType("");
         } else if (lForm.getEnDocType()!=null && lForm.getEnDocType().trim().equals(EntranceItemM.ENTRNACE_DOC_TYPE)){
             enFileTypeTemp = EntranceItemM.TELE_ITEM_TYPE;
             itemM.setEntType(lForm.getEnType());
         };
         itemM.setType(enFileTypeTemp);
         itemM.setOwner(lForm.getEnOwner());
         String role = RoleUtils.getRole(context);
         itemM.setUserRole(role);
         itemM.setEntDocType(lForm.getEnDocType());
         itemM.setOfflineCode(max);
         //itemM.setUserRole(path);
         itemM.setItemDesc(lForm.getItemDescription());
         itemM.setKeyword(lForm.getItemKeyword());

         itemM = eservice.createEn(itemM,lForm.getSubjectM(),dFileData,iszip);
         //l.getItems().put(max, itemM);
         return new Event(this, "success");
          }else {
            lForm.setErrorMode("กรุณาระบุไฟล์");
            return new Event(this, "unFile");
            }
        } 
        public Event CancelEntrance(RequestContext context) throws Exception {
         LMSForm lForm = (LMSForm) getFormObject(context);
                
             return new Event(this, "success");
        }

  


    public SubjectService getSubjectService() {
        return subjectService;
    }

    public void setSubjectService(SubjectService subjectService) {
        this.subjectService = subjectService;
    }


  

   

    public EntranceItemService getEntranceItemService() {
        return entranceItemService;
    }

    public void setEntranceItemService(EntranceItemService entranceItemService) {
        this.entranceItemService = entranceItemService;
    }

    public LessonService getLessonService() {
        return lessonService;
    }

    public void setLessonService(LessonService lessonService) {
        this.lessonService = lessonService;
    }

    public LearningItemService getLearningItemService() {
        return learningItemService;
    }

    public void setLearningItemService(LearningItemService learningItemService) {
        this.learningItemService = learningItemService;
    }
    

}
